<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\OrderAdditional;
use app\common\order\model\OrderPay;
use app\common\order\model\OrderProtocol;
use app\common\order\validate\OrderPaymentValidate;
use app\common\system\model\OperateLog;
use think\db\exception\DbException;
use think\Exception;

class Payment extends Api
{

    public function getList()
    {
        $post = $this->request->post();
        $model = new OrderPay();
        $list = $model->where('order_id', $post['order_id'])->order('id desc')->select();
        foreach ($list as $row) {
            $row->append(['type', 'user', 'store', 'check_tag']);
        }
        $result['paymentList'] = $list;

        // 酒店协议
        $protocolModel = new OrderProtocol();
        $protocolList = $protocolModel->where('order_id', $post['order_id'])->order('id desc')->select();
        foreach ($protocolList as $row) {
            $row->append(['company',  'type_tag', 'user', 'check_tag']);
        }
        $result['protocolList'] = $protocolList;

        // 增项协议
        $additionalModel = new OrderAdditional();
        $additionalList = $additionalModel->where('order_id', $post['order_id'])->where('type', 1)->select();
        foreach ($additionalList as $row) {
            $row->append(['product', 'company', 'category', 'user', 'check_tag']);
        }
        $result['additionalList'] = $additionalList;

        return success($result);
    }

    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $payment = $post['payment'];
        $validate = new OrderPaymentValidate();
        if (!$validate->check($payment)) {
            return error([], $validate->getError());
        }

        $source = [];
        // 收款信息
        $payment['user_id'] = $user['id'];
        $model = new OrderPay();
        $model->startTrans();

        $modelName = OrderPay::class;
        try {
            $model->save($payment);
            $source[$modelName] = $model->id;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new \app\common\order\model\Order();
        $order = $orderModel->where('id', $payment['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'payment'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className => $row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $payment = $post['payment'];
        $validate = new OrderPaymentValidate();
        if (!$validate->check($payment)) {
            return error([], $validate->getError());
        }

        $source = [];
        // 收款信息
        $payment['user_id'] = $user['id'];
        $model = new OrderPay();
        $model->startTrans();

        $modelName = OrderPay::class;
        try {
            $row = $model->where('id', $payment['id'])->find();
            $row->save($payment);
            $source[$modelName] = $payment['id'];
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new \app\common\order\model\Order();
        $order = $orderModel->where('id', $payment['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'payment'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className => $row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $payment = $post['payment'];
        $validate = new OrderPaymentValidate();
        if (!$validate->check($payment)) {
            return error([], $validate->getError());
        }

        // 收款信息
        // $payment['user_id'] = $user['id'];
        $model = new OrderPay();

        $model->startTrans();
        try {
            $row = $model->where('id', $payment['id'])->find();
            $origin = $row->getData();
            $row->save($payment);

            $changed = $row->getData();
            $modelName = OrderPay::class;
            OperateLog::write($user['id'], $payment['order_id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], "操作成功");
    }
}
